$NG.AllReady(function (
    page,
    {
        useDataIndexChange,
        useValuesChange,
        useUpdateRows,
        useBeforeClick,
        useUpdateRow,
        useClick
    }
) {
    const mstform = $NG.getCmpApi("p_form_employ_apply");
    const toolbarmstform = $NG.getCmpApi("toolbar_top");
    const toobaldgrid = $NG.getCmpApi("toolbar_p_form_employ_apply_d")


    if (mstform.getValues().u_ssq_state != '1') {
        toolbarmstform.insert({
            id: "getStatus",
            text: "查询上上签状态",
            iconCls: "icon-New"
        });
    }
    useClick(() => {
        getSSQstatus()
    }, "getStatus")
    function getSSQstatus() {
        // 拼接查询参数
        var url = window.location.origin + "/sd/sapwSigned/Signed/push/checkContractStatus";
        var user_contractid = mstform.getItem("u_contractid").getValue();
        var phid = mstform.getValues().phid

        if (!user_contractid || !phid) {
            $NG.alert("当前合同未推送至上上签 或 单据为审核！");
            return;
        }
        console.log(`user_contractid`, user_contractid);
        const body = { contractId: user_contractid, tabname: "p_form_employ_apply" }
        // 使用 fetch 发送 POST 请求
        fetch(url, {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(body)
        })
            .then(response => response.json())
            .then(res => {
                if (res.IsOk) {
                    $NG.alert(res.data);
                } else {
                    $NG.alert(res.data);
                }
            })
            .catch(() => {
                $NG.alert("请求失败，请稍后再试");
            });


    }
    const btn = ["save", "check"]
    btn.forEach(item => {
        useBeforeClick(async (args) => {
            let lock = true
            const arr2 = $NG.getCmpApi("p_form_employ_apply_d").getRows()
            const ceArr = []
            arr2.forEach((item, ind) => {
                console.log(item.u_isoverproof, item.u_reminder);
                if (item.u_isoverproof == '1' && !item.u_reminder) {
                    ceArr.push(ind + 1)
                    lock = false

                }
            })
            if (ceArr.length != 0) {
                $NG.alert(`超额说明为空, 第 ${ceArr.join("、")} 行`)
                return false
            }
            if (mstform.getItem("u_yg_typer").getValue() == '01') {
                if ((Number(mstform.getItem("u_total_amt").getValue()) || 0) > setSy()) {
                    lock = false
                    $NG.alert(`用工申请总额超出实施费总额当前剩余可用(${setSy()})￥`)
                }
            } else if (mstform.getItem("u_yg_typer").getValue() == '03') {
                if ((Number(mstform.getItem("u_total_amt").getValue()) || 0) > setSy(true)) {
                    lock = false
                    $NG.alert(`用工申请总额超出服务费外包总额当前剩余可用(${setSy(true)})￥`)
                }
            }
            const idcard = []
            //判断身份证号
            $NG.getCmpApi("p_form_employ_apply_d").getRows().forEach((item, index) => {
                if (!validate18DigitIDCard(String(item.idno))) {
                    idcard.push(index + 1)
                }
            })
            console.log(`idcard`, idcard);
            if (idcard.length !== 0 && mstform.getItem("u_yg_typer").getValue() != "02") {
                $NG.alert(`第 ${idcard.join("、")} 行身份证号有误！`)
                return false
            }
            if (grid.getRows().length == 0 && mstform.getItem("u_yg_typer").getValue() != "02") {
                $NG.alert("请至少给明细添加一条数据")
                return false
            }

            // 查询上上签接口逻辑

            // else {
            //     if((Number(mstform.getItem("u_total_amt").getValue()) || 0)>window._lsz_catch_ekAmt){
            //         lock = false
            //         $NG.alert(`用工申请总额超出二开费总额当前剩余可用(${window._lsz_catch_ekAmt - (Number(window?._lsz_catch_dxAmt['02']) || 0)})￥`)
            //     } 
            // }
            //判断人员是否存在问题
            const count = grid.getRows().length
            const error = []
            if (mstform.getItem("u_yg_typer").getValue() == "01" && mstform.getItem("u_yg_typer").getValue() == "03") {
                for (let i = 0; i < count; i++) {
                    const item = grid.getRows()[i]
                    console.log(item.idno);
                    await $NG.execServer("getHrCardIdIsDb", { cardid: item.idno }, (res) => {
                        console.log(res);
                        if (res.count != 0) {
                            const _data = JSON.parse(res.data)[0].extendObjects
                            let status = _data.empstatus
                            if (status == '32') {
                                error.push(i + 1)
                            }
                        }
                    })
                }
                for (let i = 0; i < count; i++) {
                    const item = grid.getRows()[i]
                    await $NG.execServer("getHrByIsBillNoDb", { username: item.u_ry_no }, (res) => {
                        console.log(res);
                        if (res.count != 0) {
                            error.push(i + 1)
                        }
                    })
                }
                if (error.length != 0) {
                    $NG.alert(`第 ${error.join("、")} 行的登录账号已存在，请更改`);
                    return false
                }
            }

            console.log(`身份证error`, error);
            if (error.length != 0) {
                $NG.alert(`第 ${error.join("、")} 行的人员在人员表已存在，并且在职`);
                return false
            }

            console.log(lock);
            return lock
        }, item)
    })
    // 过滤岗位
    cntDFilter()
    function cntDFilter() {
        $NG.updateUI(updater => updater.editGrid.p_form_employ_apply_d.u_position.setProps((p) => {
            return {
                ...p, editor: {
                    ...p.editor,
                    clientSqlFilter: `fg_simple_data.c_descript = '${mstform.getItem("u_yg_typer").getText()}'`,
                }
            };
        }));
    }
    function validate18DigitIDCard(idCard) {
        // 18 位身份证号码正则表达式，验证基本格式
        const reg = /^[1-9]\d{5}(18|19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])\d{3}[0-9Xx]$/;
        // 首先通过正则检查基本格式是否正确
        if (!reg.test(idCard)) {
            return false;
        }
        // 将身份证号码字符串转换为数组
        const idCardArray = idCard.split('');
        // 加权因子数组，用于计算前 17 位数字的加权和
        const factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
        // 校验码对应值数组，根据加权和取模的结果确定校验码
        const parity = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
        let sum = 0;
        // 计算前 17 位数字的加权和
        for (let i = 0; i < 17; i++) {
            sum += parseInt(idCardArray[i]) * factor[i];
        }
        // 获取身份证号码的最后一位，并转换为大写
        const lastChar = idCardArray[17].toUpperCase();
        // 比较计算出的校验码和实际的最后一位是否一致
        return parity[sum % 11] === lastChar;
    }

    // 示例调用
    function setSy(bool) {
        if (page.oType == 'view') return
        try {
            $NG.updateState((updater) => {
                updater.data.p_form_employ_apply.setProps({
                    u_rest_amt: (Number(window._lsz_catch_ssAmt) || 0) - (Number(window?._lsz_catch_dxAmt['01']) || 0),
                    u_rest_svc_amt: (Number(window._lsz_catch_svcAmt) || 0) - (Number(window?._lsz_catch_dxAmt['03']) || 0)
                })
            })
            if (!bool) {
                return (Number(window._lsz_catch_ssAmt) || 0) - (Number(window?._lsz_catch_dxAmt['01']) || 0)
            } else {
                return (Number(window._lsz_catch_svcAmt) || 0) - (Number(window?._lsz_catch_dxAmt['03']) || 0)
            }

        } catch (e) {
            $NG.updateState((updater) => {
                updater.data.p_form_employ_apply.setProps({
                    u_rest_amt: 0
                })
            })
            setTimeout(() => {
                console.log('重新调', e);
                setSy()
            }, 1000)
            return 0
        }
    }
    // 编辑页面逻辑

    console.log(mstform, "mstform");
    const grid = $NG.getCmpApi("p_form_employ_apply_d");
    // 编码到名称的映射
    const employmentTypeMapping = {
        "01": "实施外包用工",
        "02": "研发二次开发用工",
        "03": "服务外包用工"
    };
    const personnelcategoryMapping = {
        "01": "合同履约人员",
        "02": "项目用工",
        "03": "研发二次开发用工",
    };
    if (page.oType == 'add') {
        // $NG.updateState((updater) => {
        //     updater.data.p_form_employ_apply.setProps({
        //         u_taxrate: 0.06,
        //         bill_name: `${mstform.getItem("phid_pc").getText() || ""}定薪申请`
        //     })
        // })
        $NG.updateUI((updater) => {
            updater.editGrid.p_form_employ_apply_d.u_company.setProps({
                hidden: true
            })
        })
    }
    function setDate() {
        // 禁用
        return
        const cntstart = mstform.getItem("u_ht_startdt").getValue()
        const cntend = mstform.getItem("u_ht_enddt").getValue()
        if (cntstart && cntend) {
            //计算时间差
            const cha = monthsBetweenDates(cntstart, cntend)
            $NG.updateState((updater) => {
                updater.data.p_form_employ_apply.setProps({
                    u_ht_mouth: cha
                })
            })
        }
    }
    {
        //合同时间
        useValuesChange(({ args }) => {
            setDate()
        }, "p_form_employ_apply.u_ht_startdt")

        useValuesChange(({ args }) => {
            setDate()
        }, "p_form_employ_apply.u_ht_enddt")
        useValuesChange(({ args }) => {
            sumAmt()
        }, ["p_form_employ_apply.u_amt_jbf","p_form_employ_apply.u_amt_ylsb"])

        useValuesChange(({ args }) => {
            const phid = mstform.getItem("u_wb_company").getValue()
            $NG.updateState((updater) => {
                updater.data.p_form_employ_apply.setProps({
                    phid_supply_ent: {
                        label: mstform.getItem("u_wb_company").getText(),
                        value: mstform.getItem("u_wb_company").getValue()
                    }
                })
            })
            $NG.execServer("getSuppyPhone", { phid }, (res) => {
                if (res.count == 0) return
                const _data = JSON.parse(res.data)[0].extendObjects
                $NG.updateState((updater) => {
                    updater.data.p_form_employ_apply.setProps({
                        u_contact_information: _data.phone
                    })
                })
            })
        }, "p_form_employ_apply.u_wb_company")

        useValuesChange(({ args }) => {
            sumAmt()
        }, "p_form_employ_apply.sumAmt()")
        //表头字段变化逻辑
        useValuesChange(({ args }) => {
            var u_yg_typer = mstform.getItem("u_yg_typer").getValue();
            console.log(u_yg_typer, "u_yg_typer");
            var grid = $NG.getCmpApi("p_form_employ_apply_d");
            console.log(grid, "grid");
            var data = grid.getData();
            // 将编码转换为名称
            var employmentTypeName = employmentTypeMapping[u_yg_typer] || u_yg_typer;
            data.forEach(function (item) {
                item.u_employment_type = u_yg_typer;
                item.u_employment_type_EXName = employmentTypeName; // 添加转换后的名称
                gridhandle(item);
            });
            grid.updateRow(data);
            console.log(`测试`, mstform.getItem("u_yg_typer").getValue());
            console.log(`隐藏`);
            if(mstform.getItem("u_yg_typer")?.getValue() == '02'){
                $NG.updateState((updater)=>{
                    updater.data.p_form_employ_apply.setProps({
                        u_sfxyssq:'01'
                    })
                })
            }
            setHiddens()
            getFormName()
            cntDFilter()
            grid.refreshView()
        }, "p_form_employ_apply.u_yg_typer");
        setHiddens()
        function setHiddens() {
            if (!mstform.getItem("u_yg_typer").getValue()) return
            const _arr = ["u_name", "u_total_amt", "u_ry_no",
                "u_ht_qty", "idno", "u_service_amt", "u_amt",
                "u_fw_total", "u_total_amt", "u_contact",
                "u_age", "u_graduatedschool", "u_major",
                "u_worklife", "u_real_dt", "u_sex",
                "u_contact", "u_age", "u_graduatedschool",
                "u_major", "u_worklife", "u_fw_total",
                "u_real_dt", "u_bmxy", "u_amt_sb", "u_fund", "u_amt_other", "u_amt_vat", "u_dtotal_amt_vat"]
            _arr.forEach((element) => {
                try {
                    if (mstform.getItem("u_yg_typer").getValue() == "02") {
                        $NG.updateUI((updater) => {
                            updater.editGrid.p_form_employ_apply_d[
                                element
                            ].setProps({
                                hidden: true,
                                disable: true,
                            });
                        });
                        $NG.updateUI((updater) => {
                            updater.editGrid.p_form_employ_apply_d.u_contact.setProps({
                                required: false,
                            });
                        });
                        if (
                            element == "u_cntend_dt" ||
                            element == "u_ht_qty" ||
                            element == "u_cntstart_dt_new" ||
                            element == "u_name" ||
                            element == "u_wage_standard" ||
                            element == "idno" ||
                            element == "u_contact" ||
                            element == "u_ry_no"
                        ) {
                            $NG.updateUI((updater) => {
                                updater.editGrid.p_form_employ_apply_d[
                                    element
                                ].setProps({
                                    required: false,
                                });
                            });
                        }
                    } else {
                        console.log(`释放`);
                        $NG.updateUI((updater) => {
                            console.log(`释放参`,element,updater.editGrid.p_form_employ_apply_d[
                                element
                            ]);
                            updater.editGrid.p_form_employ_apply_d[
                                element
                            ].setProps({
                                hidden: false,
                                disable: false,
                            });
                        });
                        $NG.updateUI((updater) => {
                            updater.editGrid.p_form_employ_apply_d.u_contact.setProps({
                                required: true,
                            });
                        });
                        if (
                            element == "u_cntend_dt" ||
                            element == "u_ht_qty" ||
                            element == "u_cntstart_dt_new" ||
                            element == "u_name" ||
                            element == "u_wage_standard" ||
                            element == "idno" ||
                            element == "u_contact" ||
                            element == "u_ry_no"
                        ) {
                            $NG.updateUI((updater) => {
                                updater.editGrid.p_form_employ_apply_d[
                                    element
                                ].setProps({
                                    required: true,
                                });
                            });
                        }
                    }
                } catch (e) {
                    console.log(`字段丢失`, element, e);
                }
            });


            const headArr = ["u_rest_svc_amt","u_amt_jbf","u_ht_enddt", "u_ht_startdt", "u_total_amt", "u_wb_company", "u_ht_mouth", "u_fw_amt", "u_rest_amt", "u_total_amt_vat", "phid_customer_ent", "u_jfdw_tel", "u_contact_information"]
            headArr.forEach(item => {
                if (mstform.getItem("u_yg_typer").getValue() == '02') {
                    $NG.updateUI((updater) => {
                        updater.fieldSetForm.p_form_employ_apply[item].setProps({
                            hidden: true,
                            disable: true,
                            required: false
                        })
                    });
                } else {
                    $NG.updateUI((updater) => {
                        updater.fieldSetForm.p_form_employ_apply[item].setProps({
                            hidden: false,
                            disable: false,
                            required: true
                        })
                    });
                }

            })
            grid.refreshView()
        }
        useValuesChange(({ args }) => {
            var phid_pc = mstform.getItem("phid_pc").getValue();
            var pc = mstform.getItem("phid_pc").getRawValue();
            var grid = $NG.getCmpApi("p_form_employ_apply_d");
            var data = grid.getData();
            data.forEach(function (item) {
                item.phid_pc = phid_pc;
                item.phid_pc_EXName = pc;
            });
            grid.updateRow(data);
            getTowOnTotalAmt()
            getSsTotalAmt()
            getOuterPayFrom()
            getSvcZgxcTotalAmt()
            getPtInfoByPhid()
        }, "p_form_employ_apply.phid_pc");
    }

    function getPtInfoByPhid() {
        const phid = mstform.getItem("phid_pc").getValue()
        $NG.execServer("getPtInfoByPhid", { phid }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects

            $NG.execServer("getCwhsZZ", { phid: _data.cwhszz }, (res) => {
                if (res.count == 0) return
                const datas = JSON.parse(res.data)[0].extendObjects
                $NG.updateState((updater) => {
                    updater.data.p_form_employ_apply.setProps({
                        phid_customer_ent: {
                            label: datas.compname,
                            value: datas.phid
                        },
                    })
                })
            })
        })
    }
    if (page.oType == 'add') {

    }
    useValuesChange(({ args }) => {
        const _arr = grid.getRows()
        _arr.forEach(item => {
            item.u_service_amt = (Number(mstform.getItem("u_fw_amt").getValue()) || 0)
        })
        grid.refreshView()
    }, "p_form_employ_apply.u_fw_amt")
    {
        // 明细订阅字段编辑
        useDataIndexChange(({ args, instance }) => {
            const record = args[0];
            gridhandle(record);
            instance.updateRow(args[0]);
        }, "u_personnel_category");
        useDataIndexChange(({ args, instance }) => {
            const record = args[0];
            gridhandle(record);
            getFormName()
            instance.updateRow(args[0]);
        }, "u_employment_type");
    }

    //设置的单据名称
    function getFormName() {
        console.log(`改名`);
        const darr = grid.getRows()
        let name = darr.reduce((value, item, index) => {
            if (index < 2) {
                return value + "、" + (String(item.u_name || ""))
            }
            return value
        }, "")
        //拿到日期间隔
        let days = `(${new Date(mstform.getItem("u_ht_startdt").getValue()).getMonth() + 1}月 - ${new Date(mstform.getItem("u_ht_enddt").getValue()).getMonth() + 1}月)`

        if (mstform.getItem("u_yg_typer").getValue() == '02') {
            $NG.updateState((updater) => {
                updater.data.p_form_employ_apply.setProps({
                    u_taxrate: 0.06,
                    bill_name: `${mstform.getItem("phid_pc").getText() || ""}定薪申请`,
                    u_sffw: 'ss'
                })
            })
        } else {
            $NG.updateState((updater) => {
                updater.data.p_form_employ_apply.setProps({
                    bill_name: `劳务派遣${days} - ${name}等`,
                    u_taxrate: 0.06,
                })
            })
        }
    }
    // 表体数据变化（增行、删行、引入）时，汇总计算至表头
    useUpdateRows(({ args }) => {
        getFormName()
        console.log('监听表', args);

        sumAmt()
    }, "p_form_employ_apply_d");

    function sumAmt() {
        var sumAmt = 0;
        var sumAmtVat = 0
        const rows = grid.getRows()
        isOne(rows)
        let service_amt_total = 0
        let b = '2'
        rows.forEach((items) => {
            if (!items.u_ry_zt) {
                items.u_ry_zt = '32'
                items.u_ry_zt_EXName = '在职'
            }
            try {
                items.u_company = mstform.getItem("u_wb_company").getValue()
                items.u_company_EXName = mstform.getItem("u_wb_company").getText()
            } catch (e) { }
            // items.u_ht_qty = monthsBetweenDates(items.u_cntstart_dt_new ,items.u_cntend_dt)
            items.u_service_amt = 48
            let sexAmtSum = ((Number(items.u_wage_standard) || 0)
                + (Number(items.u_fund) || 0)
                /*+ (Number(items.u_service_amt) || 0) 月费用不需加服务费---人资国庆*/
                + (Number(items.u_amt_sb) || 0)
                + (Number(items.u_amt_other) || 0)
                + (Number(items.u_amt_rate) || 0))
            items.u_amt = sexAmtSum;
            items.u_amt_vat = sexAmtSum * 1.0672 + (Number(items.u_service_amt) || 0);
            items.u_total_amt = (Number(items.u_amt) || 0) * (Number(items.u_ht_qty) || 0) 
            items.u_dtotal_amt_vat = (Number(items.u_amt_vat) || 0) * (Number(items.u_ht_qty) || 0)
            service_amt_total += (Number(items.u_fw_total) || 0)
            sumAmt += (Number(items.u_total_amt) || 0);
            sumAmtVat += (Number(items.u_dtotal_amt_vat) || 0)
            if (items.u_wage_standard - items.u_salary_ceiling > 0) {
                b = '1'
            }
        });
        // 汇总赋值
        let jbAmt = Number(mstform.getItem("u_amt_jbf").getValue())
        console.log(jbAmt, 'jbAmt');
        console.log(sumAmt, 'sumAmt');

        $NG.updateState((updater) => {
            updater.data.p_form_employ_apply.setProps({
                u_total_amt: jbAmt + +Number(sumAmt) + (Number(mstform.getItem("u_amt_ylsb")?.getValue()) || 0),
                u_fw_amt: service_amt_total,
                u_total_amt_vat: sumAmtVat + jbAmt + + (Number(mstform.getItem("u_amt_ylsb")?.getValue()) || 0),
                u_sf_overamt: b
            });
        });
        grid.refreshView()
    }

    const key_ = ["u_wage_standard", "u_fund", "u_position", "u_qualification_grade"]
    key_.forEach(item => {
        useDataIndexChange(
            ({ args, table }) => {
                var gridTab = $NG.getCmpApi("p_form_employ_apply_d");
                var row = args[0];
                var u_amt = args[0].u_amt;
                var u_salary_ceiling = args[0].u_salary_ceiling;
                var u_wage_standard = args[0].u_wage_standard
                console.log("args表体数据", "args表体数据");
                if (u_wage_standard - u_salary_ceiling > "0") {
                    row.u_isoverproof = "1";

                    $NG.message("当前行，超标准了")
                } else {
                    row.u_isoverproof = "0";
                }

                gridTab.updateRow(row); // 更新当前行数据
                gridTab.refreshView();
            },
            item
        ); //监听的变化的字段
    })

    function debounce(fn, delay) {
        //防抖
        let timer = null;
        return function () {
            if (timer) {
                clearTimeout(timer);
            }
            timer = setTimeout(() => {
                fn.apply(this, arguments);
                timer = null;
            }, delay);
        };
    }
    useUpdateRow(({ args, table }) => {
        const record = args[0];
        record.u_service_amt = 48
        record.u_fw_total = (Number(record.u_ht_qty) || 0) * (Number(record.u_service_amt) || 0)
        const { u_qualification_grade, u_position, u_residence } = record;
        //判断是否超标准
        const _count = Number(record.u_wage_standard) - Number(record.u_salary_ceiling)
        console.log(`是否超标准`, _count, record);
        if (_count > 0) {
            record.u_isoverproof = "1"
            record.u_isoverproof_EXName = "是"
        } else {
            record.u_isoverproof = "0"
            record.u_isoverproof_EXName = "否"
        }
        //判断月数是否超出
        // if ((Number(record.u_ht_qty) || 0) > (Number(mstform.getItem("u_ht_mouth").getValue()) || 0)) {
        //     record.u_ht_qty = null
        //     $NG.alert("当前行的派遣月数超出合同月数！")
        // }
        var idno = record.idno;
        // if (idno) {
        //     // 获取 name 为 "idno" 的第一个输入框元素
        //     var idCardInput = document.getElementsByName("idno")[0];
        //     // 每次失去焦点时触发校验
        //     idCardInput?.addEventListener("blur", async function () {
        //         const idCard = idCardInput.value;
        //         const isValid = validateIdCard(idCard);
        //         if (isValid) {
        //             // 校验通过，执行其他逻辑
        //             $NG.execServer("getFg3UserInfoByUserno", { userno: idno }, function (res) {
        //                 if (res.count > 0) {
        //                     const data = JSON.parse(res.data)[0].extendObjects; //单返回值
        //                     record.u_name = data.username;
        //                     dgrid.refreshView();
        //                 }
        //             });
        //             console.log("身份证号合法");
        //         } else {
        //             $NG.message("当前行身份证号不合法")
        //             record.idno = "不合法身份证请重新输入";
        //         }
        //     });
        // }
        // console.log(u_qualification_grade, u_position, u_residence, "打印的值");
        if (u_qualification_grade && u_position && u_residence) {
            console.log(
                u_qualification_grade,
                u_position,
                [110100, 440100, 310100, 440300].includes(u_residence) ? "01" : "02"
            );
            $NG.execServer("getIsposiAndCno", { city: [110100, 440100, 310100, 440300].includes(u_residence) ? "01" : "02", u_position: u_position }, function (res) {
                try {
                    console.log(res);
                    const _data = JSON.parse(res.data)[0].extendObjects
                    const _tempIdArr = []
                    JSON.parse(res.data).forEach(item => {
                        _tempIdArr.push(item.extendObjects.c_no)
                    });
                    console.log(`匹配等级查询`, _tempIdArr);
                    const _mapGrade = {
                        id8570000000000292: "01",
                        id8570000000000293: "02",
                        id8570000000000294: "03",
                    }
                    if (_tempIdArr.indexOf(_mapGrade["id" + u_qualification_grade]) !== -1) {

                    } else {
                        record.u_qualification_grade = null;
                        record.u_qualification_grade_EXName = null;
                        grid.refreshView()
                        $NG.message('当前岗位没有该“薪资等级”选择项~~');
                        $NG.message('当前岗位没有该“薪资等级”选择项~~');
                        $NG.message('当前岗位没有该“薪资等级”选择项~~');
                        return
                    }
                    const xl = mstform.getItem("u_yg_typer").getValue() == '02' ? `p.u_educational_require = '${record.u_education}'` : '1=1'
                    // 查找相应的薪资
                    $NG.execServer(
                        "getPriceTop1",
                        {
                            qg: u_qualification_grade,
                            pe: u_position,
                            cc: [110100, 440100, 310100, 440300].includes(u_residence)
                                ? "01"
                                : "02",
                            xl: xl
                        },
                        function (res) {
                            try {
                                console.log(`查询薪资`, res);
                                const data = JSON.parse(res.data);
                                const PriceTop = data[0].extendObjects.u_sal_limit_standard;
                                if (PriceTop) {
                                    record.u_salary_ceiling = PriceTop;
                                } else {
                                    record.u_salary_ceiling = "未查询到数据";
                                }
                                // $NG.updateState((updater) => {
                                // 	updater.data.p_form_employ_apply.setProps({
                                // 		u_bu: { value: zz, label: zz_oname },
                                // 		u_product_line: { value: cpx, label: cpx_name },
                                // 		u_xmjl: { value: xmjl, label: xmjl_name },
                                // 		u_regional_center: { value: qyzx, label: qyzx_name },
                                // 		u_pc_no: pc_no,
                                // 	});
                                // });
                                grid.refreshView();
                            } catch (err) { }
                        }
                    );
                } catch (err) {
                    args[0].u_qualification_grade = null;
                    args[0].u_qualification_grade_EXName = null;
                    console.log(err);
                    grid.refreshView()
                    $NG.alert('没有相应的资金等级或者岗位没有数据~~');
                }
            })


        } else {
            record.u_salary_ceiling = "";
            grid.refreshView();
        }

        console.log(record, "record");
    }, "p_form_employ_apply_d");
    // 项目名称变化时自动带入产品线、事业部
    useValuesChange(({ args }) => {
        console.log(args[0], "aaaa1111");
        const phid_pc = args[0].phid_pc.value;
        if (phid_pc) {
            console.log(phid_pc);
            getProInfo()
        }
    }, "p_form_employ_apply.phid_pc");
    getProInfo()
    function getProInfo() {
        $NG.execServer("getProjInfo", { pc: mstform.getItem("phid_pc").getValue() }, function (res) {
            if (res.count == 0 || !res.data) return
            const data = JSON.parse(res.data);
            const zz = data[0].extendObjects.zz;
            const zz_oname = data[0].extendObjects.oname;
            const cpx = data[0].extendObjects.cpx;
            const cpx_name = data[0].extendObjects.cname;
            const xmjl = data[0].extendObjects.xmjl;
            const xmjl_name = data[0].extendObjects.xmjl_name;
            const qyzx = data[0].extendObjects.qyzx;
            const qyzx_name = data[0].extendObjects.qyzx_name;
            const pc_no = data[0].extendObjects.pc_no;

            $NG.updateState((updater) => {
                updater.data.p_form_employ_apply.setProps({
                    u_bu: { value: zz, label: zz_oname },
                    u_product_line: { value: cpx, label: cpx_name },
                    u_xmjl: { value: xmjl, label: xmjl_name },
                    u_regional_center: { value: qyzx, label: qyzx_name },
                    u_pc_no: pc_no,
                });
            });
        });
    }
    // 添加行前的处理
    useBeforeClick(async function ({ args }) {
        try {
            // 获取表单字段值
            var u_yg_typer = mstform.getItem("u_yg_typer").getValue();
            var yg_type = mstform.getItem("u_yg_typer").getRawValue();
            var phid_pc = mstform.getItem("phid_pc").getValue();
            var pc = mstform.getItem("phid_pc").getRawValue();

            // 将编码转换为名称
            var employmentTypeName = employmentTypeMapping[u_yg_typer] || u_yg_typer;

            // 检查 grid 是否已定义
            if (!grid) {
                console.error("Grid is not defined");
                return false; // 取消向下执行
            }

            // 添加行到网格
            grid.addRows({
                u_employment_type: u_yg_typer,
                u_employment_type_EXName: employmentTypeName, // 添加转换后的名称
                phid_pc: phid_pc,
                phid_pc_EXName: pc,
            });

            // 刷新视图
            if (typeof grid.refreshView === "function") {
                grid.refreshView();
            } else {
                console.error("refreshView method is missing on grid");
            }

            return false; // 取消向下执行
        } catch (error) {
            console.error("Error in useBeforeClick:", error);
            return false; // 取消向下执行
        }
    }, "addrow");

    function gridhandle(record) {
        if (mstform.getItem("u_yg_typer").getValue() == "02") {
            $NG.updateUI((updater) => {
                updater.editGrid.p_form_employ_apply_d.u_personnel_category.setProps(
                    {
                        disabled: true, // 只读
                    }
                );
            });
            record.u_personnel_category = "03";
            record.u_personnel_category_EXName = "研发二次开发用工";
        } else {
            $NG.updateUI((updater) => {
                updater.editGrid.p_form_employ_apply_d.u_personnel_category.setProps({
                    disabled: false, //只读
                });
            });
            if (record.u_personnel_category == "03") {
                record.u_personnel_category = "";
                record.u_personnel_category_EXName = "";
                // $NG.alert("用工类型选择了实施外包用工，人员类别只能选合同履约人员和项目用工");
            }
        }
    }
    //获取实施费用二开费用
    getSsTotalAmt()
    function getSsTotalAmt() {
        if (!mstform.getItem("phid_pc").getValue()) return
        $NG.execServer("getSsTotalAmtM", { phid_pc: mstform.getItem("phid_pc").getValue() }, (res) => {
            console.log(`实施`, res);
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            console.log(`实施`, _data);
            window._lsz_catch_ssAmt = (Number(_data.total_amt) || 0)
            setSy()
        })
    }
    // 获取服务外包费用
    getSvcZgxcTotalAmt()
    function getSvcZgxcTotalAmt() {
        if (!mstform.getItem("phid_pc").getValue()) return
        $NG.execServer("getSvcZgxcTotalAmt", { phid_pc: mstform.getItem("phid_pc").getValue() }, (res) => {
            console.log(`服务`, res);
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            console.log(`服务`, _data);
            window._lsz_catch_svcAmt = (Number(_data.total_amt) || 0)
            setSy()
        })
    }
    //获取预算研发二开费用
    getTowOnTotalAmt()
    function getTowOnTotalAmt() {
        if (!mstform.getItem("phid_pc").getValue()) return
        $NG.execServer("getImplTowTotalAmt", { phid_pc: mstform.getItem("phid_pc").getValue() }, (res) => {
            if (res.count == 0) return
            const _data = JSON.parse(res.data)[0].extendObjects
            console.log(`二开`, _data);
            window._lsz_catch_ekAmt = (Number(_data.total_amt) || 0)
            setSy()
        })
    }
    //获取定薪和
    getOuterPayFrom()
    function getOuterPayFrom() {
        if (!mstform.getItem("phid_pc").getValue()) return
        $NG.execServer("getOuterPayDx", { phid_pc: mstform.getItem("phid_pc").getValue() }, (res) => {
            if (res.count == 0) {
                window._lsz_catch_dxAmt = {}
                window._lsz_catch_dxAmt['01'] = 0
                window._lsz_catch_dxAmt['02'] = 0
                window._lsz_catch_dxAmt['03'] = 0
                return
            }
            const _data = JSON.parse(res.data)
            console.log(`定薪`, _data);
            window._lsz_catch_dxAmt = _data.reduce((value, item) => {
                console.log(item, item.extendObjects);
                console.log(item.extendObjects.u_yg_typer,);
                if (item.extendObjects.u_yg_typer == '01') {
                    value['01'] = (Number(item.extendObjects.total_amt) || 0)
                } else if (item.extendObjects.u_yg_typer == '02') {
                    value['02'] = (Number(item.extendObjects.total_amt) || 0)
                } else {
                    value['03'] = (Number(item.extendObjects.total_amt) || 0)
                }
                return value
            }, {})
            console.log(`定薪`, window._lsz_catch_dxAmt);
            setSy()
        })
    }

});
function validateIdCard(idCard) {
    // 首先将输入的身份证号码统一转换为大写形式，方便后续校验和比较，避免大小写不一致导致的问题
    idCard = idCard.toUpperCase();

    // 定义错误信息数组，用于收集校验过程中发现的所有错误信息
    const errors = [];

    // 1. 长度校验
    if (idCard.length !== 18) {
        errors.push("身份证号长度必须为18位");
        return false;
    }

    // 2. 整体格式校验，确保每一位都是合法字符（前17位为数字，第18位为数字或者X）
    for (let i = 0; i < idCard.length; i++) {
        const char = idCard.charAt(i);
        if (i < 17 && isNaN(parseInt(char))) {
            // 前17位中如果出现非数字字符，直接判定为非法输入
            errors.push("身份证号前17位必须全部为数字");
            return false;
        }
        if (i === 17 && char !== "X" && isNaN(parseInt(char))) {
            // 第18位如果不是数字也不是X，判定为非法输入
            errors.push("身份证号第18位必须是数字或者X");
            return false;
        }
    }

    // 3. 地区代码校验（这里简单校验前6位是否为数字，实际应用中应该和标准地区代码库比对）
    const areaCode = idCard.substring(0, 6);
    if (!/^\d{6}$/.test(areaCode)) {
        errors.push("身份证号前6位地区代码不合法");
        return false;
    }

    // 4. 出生日期校验
    const birthYear = parseInt(idCard.substring(6, 10), 10);
    const birthMonth = parseInt(idCard.substring(10, 12), 10);
    const birthDay = parseInt(idCard.substring(12, 14), 10);

    // 校验年份范围是否合理（简单判断在合理区间内，实际应用可根据业务需求细化）
    if (birthYear < 1900 || birthYear > new Date().getFullYear()) {
        errors.push("身份证号中的出生年份不合法");
        return false;
    }

    // 校验月份范围是否合理（1 - 12月）
    if (birthMonth < 1 || birthMonth > 12) {
        errors.push("身份证号中的出生月份不合法");
        return false;
    }

    // 根据月份判断该月最大天数，校验日期是否合理
    const monthDays = [
        31,
        28 +
        ((birthYear % 4 === 0 && birthYear % 100 !== 0) || birthYear % 400 === 0
            ? 1
            : 0),
        31,
        30,
        31,
        30,
        31,
        31,
        30,
        31,
        30,
        31,
    ];
    if (birthDay < 1 || birthDay > monthDays[birthMonth - 1]) {
        errors.push("身份证号中的出生日期不合法");
        return false;
    }

    // 创建日期对象来再次验证日期的合法性（考虑边界情况等）
    const date = new Date(birthYear, birthMonth - 1, birthDay);
    if (
        date.getFullYear() !== birthYear ||
        date.getMonth() + 1 !== birthMonth ||
        date.getDate() !== birthDay
    ) {
        errors.push("身份证号中的出生日期不合法");
        return false;
    }

    // 5. 校验码校验
    const weightFactors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const checkCodes = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];

    let sum = 0;
    for (let i = 0; i < 17; i++) {
        sum += parseInt(idCard.charAt(i), 10) * weightFactors[i];
    }

    const checkCode = checkCodes[sum % 11];
    if (idCard.charAt(17) !== checkCode) {
        errors.push("身份证号校验码不正确");
        return false;
    }

    // 如果所有校验都通过，说明身份证号合法
    console.log("身份证号合法");
    return true;
}

// 人员类别和用工类别唯一且细节判断
function isOne(arr) {
    const mstform = $NG.getCmpApi("p_form_employ_apply");
    try {
        arr.forEach(item => {
            if (mstform.getItem("u_yg_typer").getValue() == '02') {
                item.u_personnel_category = '03'
                item.u_personnel_category_EXName = '研发二次开发用工'
            }
            if (item.u_employment_type.split(",").length > 1) {
                item.u_employment_type = item.u_employment_type.split(",")[0]
                item.u_employment_type_EXName = item.u_employment_type_EXName.split(",")[item.u_employment_type_EXName.split(",").length - 1]
            } else if (item.u_personnel_category.split(",").length > 1) {
                if (item.u_employment_type_EXName == "实施外包用工" || item.u_employment_type == '01') {
                    item.u_personnel_category = item.u_personnel_category.split(",")[item.u_personnel_category.split(",").length - 1]
                    item.u_personnel_category_EXName = item.u_personnel_category_EXName.split(",")[item.u_personnel_category_EXName.split(",").length - 1]
                    if (item.u_personnel_category == "03" || item.u_personnel_category_EXName == "研发二次开发用工") {
                        item.u_personnel_category = ""
                        item.u_personnel_category_EXName = ""
                    }
                } else {
                    item.u_personnel_category = item.u_personnel_category.split(",")[item.u_personnel_category.split(",").length - 1]
                    item.u_personnel_category_EXName = item.u_personnel_category_EXName.split(",")[item.u_personnel_category_EXName.split(",").length - 1]
                }
            }
        })


        $NG.getCmpApi("p_form_employ_apply_d").refreshView()
    } catch (er) {
        console.log(`错误`, er);
    }
}

function monthsBetweenDates(date1Str, date2Str) {
    // 将字符串转换为 Date 对象
    const date1 = new Date(date1Str);
    const date2 = new Date(date2Str);

    // 确保 date2 是较晚的日期
    if (date1 > date2) {
        [date1, date2] = [date2, date1];
    }

    // 计算两个日期之间的毫秒数差值
    const timeDiff = date2.getTime() - date1.getTime();

    // 将毫秒数差值转换为天数差值，因为一天有 24 小时，每小时 60 分钟，每分钟 60 秒，每秒 1000 毫秒
    const dayDiff = Math.abs(timeDiff / (1000 * 60 * 60 * 24)) + 1; // 加 1 是为了包含起始和结束日期

    // 计算月数，用天数除以 30
    const months = dayDiff / 30;

    // 保留两位小数
    return parseFloat(months.toFixed(2));
}

// select p.phid_org syb, fg.oname oname , p.user_product_line cpx, s.c_name cname, p.bill_no pc_no, p.project_manager xmjl, he.bill_name xmjl_name from project_table p left join fg_orglist fg on fg.phid=p.phid_org left join fg_simple_data s on s.phid=p.user_product_line left join hr_epm_main he on he.phid=p.project_manager where p.phid=@pc

// select p.u_position gangwei,p.u_residence ,p.u_qualification_grade zizhidengji where p.phid=@pc
